package lhz.confirm;

import com.rabbitmq.client.Channel;
import lhz.RabbitMqUtils;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/10/22 14:08
 * @Description:
 **/
public class BatchProducer {
    /**
     * 设置队列名称
     */
    private final static String QUEUE_NAME = "confirm_queue";

    /**
     * 发送消息数量
     */
    private final static Integer MESSAGE_COUNT = 500;

    public static void main(String[] args) throws Exception {
        try (Channel channel = RabbitMqUtils.getChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            // 开启发布确认
            channel.confirmSelect();
            // 批量确认消息大小
            int batchSize = 100;
            // 未确认消息个数
            int outstandingMessageCount = 0;
            long begin = System.currentTimeMillis();
            for (int i = 0; i < MESSAGE_COUNT; i++) {
                String message = i + "";
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                outstandingMessageCount++;
                // 达到设置的批处理大小时，进行确认
                if (outstandingMessageCount == batchSize) {
                    channel.waitForConfirms();
                    outstandingMessageCount = 0;
                }
            }
            // 为了确保还有剩余没有确认消息，进行再次确认
            if (outstandingMessageCount > 0) {
                channel.waitForConfirms();
            }
            long end = System.currentTimeMillis();
            System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息,耗时" + (end - begin) + "ms");
        }
    }
}
